/**
 * LY.com Inc.
 * Copyright (c) 2004-2019 All Rights Reserved.
 */
package com.gitee.kamismile.disruptorEx.commandhandling.gateway;

import com.gitee.kamismile.disruptorEx.commandhandling.disruptor.CommandHandlingEntry;
import com.lmax.disruptor.dsl.Disruptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author dong.li
 * @version $Id: DisruptorServer, v 0.1 2019/5/29 10:47 dong.li Exp $
 */
@Component
public class DisruptorServer {

    @Autowired
    private DisruptorConfiguration disruptorConfiguration;

    @Bean
    public Disruptor<CommandHandlingEntry> getDisruptor(
            @Qualifier("threadPoolTaskExecutorforDisruptor") ThreadFactory threadPoolTaskExecutorforDisruptor
    ) {
        return new Disruptor<CommandHandlingEntry>(CommandHandlingEntry::new, disruptorConfiguration.getBufferSize(),
                threadPoolTaskExecutorforDisruptor,
                disruptorConfiguration.getProducerType(),
                disruptorConfiguration.getWaitStrategy());
    }

    @Bean
    public DefaultCommandGateway getDefaultCommandGateway(Disruptor<CommandHandlingEntry> disruptor) {
        return new DefaultCommandGateway(disruptor, disruptorConfiguration);
    }


    @Bean("threadPoolTaskExecutorforDisruptor")
    public ThreadFactory getThreadPoolTaskExecutorforDisruptor(DisruptorConfiguration disruptorConfiguration) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(disruptorConfiguration.getCorePoolSize());
        threadPoolTaskExecutor.setMaxPoolSize(disruptorConfiguration.getMaxPoolSize());
        threadPoolTaskExecutor.setQueueCapacity(disruptorConfiguration.getQueueCapacity());
        threadPoolTaskExecutor.setThreadGroupName("disruptor-thread-pool-");
        threadPoolTaskExecutor.setThreadNamePrefix("disruptor-executor-thread-");
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }

}
